<?php
if (!ob_start("ob_gzhandler")) {
  ob_start();
}

require_once '../include/config.php';
require_once '../include/utils.class.php';
require_once '../include/orm.class.php';
require_once '../3rd_party/MPDF56/mpdf.php';

session_name(SESSION);
session_start();

$orm = new ORM();

$__sys = Utils::get_param('__sys', NULL);
$order_number = Utils::get_param('od', NULL);

if (!isset($_SESSION[SYS . $__sys])) {
  die('Session Not Found');
}

$app_data = $_SESSION[SYS . $__sys];

if ($app_data->sys->login_required == 1 && (!(isset($app_data->is_authorised)) || $app_data->is_authorised == 0)) {
  die('Not Authenticated');
}

$opts = new stdClass();
$opts->cd = 't.order_number = :v1';
$opts->cdv = array(':v1' => $order_number);
$data = $orm->get('pb_ecom_order', NULL, NULL, NULL, NULL, $opts)->d;

if (count($data) > 0) {
  
  $opts = new stdClass();
  $opts->cd = 't.order_id = :v1';
  $opts->cdv = array(':v1' => $data[0]->id);
  $data[0]->__purchases = $orm->get('pb_ecom_purchase', NULL, NULL, NULL, NULL, $opts)->d;
  
  if (!isset($_SESSION['profile'])) {
    $rslt = $orm->get('pb_ecom_admin', NULL, NULL, NULL, NULL, NULL)->d;
    if (count($rslt) > 0) {
      $_SESSION['profile'] = $rslt[0];
    }
  }
  
  $data[0]->__shop = $_SESSION['profile']->shop_name;
  $postdata = http_build_query(
    array(
      'od' => json_encode($data[0])
    )
  );
  $opts = array('http' =>
    array(
      'method'  => 'POST',
      'header'  => 'Content-type: application/x-www-form-urlencoded',
      'content' => $postdata
    )
  );
  $context  = stream_context_create($opts);
  
  $mpdf = new mPDF('c'); 
  $mpdf->SetDisplayMode('fullpage');
  // LOAD a stylesheet
  $stylesheet = file_get_contents(URL . HOME_DIR . '__od.php', true, $context); 
  $mpdf->WriteHTML($stylesheet);
  
  $mpdf->Output($order_number . '.pdf', 'D');
}
?>